

this.view = {extend: "base" };

this.handler = function(){
	
	var page = [], output = [], processedItems =[], user = request.params.user, prettyDate = new PrettyDate.converter();
	
	var replyRetriever = function(lastPost, replies){
		var returnValue = null;
		
		replies.forEach(function(reply){
			if(reply.value.id == lastPost.parentId && (lastPost.toUserId != reply.value.toUserId)){
				returnValue = reply.value;
			}
		});
		return returnValue;
	}
	
	var conversationUsersString = function(convoUsers){
		var returnValue = [], done = [];
		convoUsers.forEach(function(user, i){
			if(done.indexOf(user) < 0){
				(i > 0)
					? returnValue.unshift(", <a href='/hackerfeed/"+ user+"?" + request.queryString + "' class='insite'>"+user+"</a>")
					: returnValue.unshift(" and <a href='/hackerfeed/"+ user+"?" + request.queryString + "' class='insite'>"+user+"</a> ");
				done.push(user);
			}
		});
		return returnValue.join("");
	}
	
	this.get = function(){
		
		storage.items.get({
			where: {
				userId: request.uri.tokens.user || request.params.user, 
				type: "comment"},
			order: {"pubDate": "desc"},
			count: 15
		}).forEach(function(row, i){
			
			var item = row.value;
			if(processedItems.indexOf(item.id) < 0){
				//alert(item.commentHTML)
				item.replies = storage.items.get({where: {parentId: item.id }});
				var section, added;
				
				var starterFinder = function(item){
					var starterItem = storage.items.getSingle({id: item.parentId}).value;
					if(starterItem.type == "comment" && ((section.conversationWith.indexOf(starterItem.userId) > -1 || (starterItem.userId == section.user)) || (request.params.user && ((typeof(request.params.user) == "object" && request.params.user.indexOf(starterItem.userId) > -1) || request.params.user == starterItem.userId)))){
						starterItem.replies = storage.items.get({where: {parentId: starterItem.id }});
						section.posts.unshift(starterItem);
						processedItems.push(starterItem.id);
						if(starterItem.isUserReply){
							starterFinder(starterItem)
						} else {
							section.replyToComment = null;
						}
					} else {
						section.replyToComment = starterItem.userId;
						section.replyToId = starterItem.parentId;	
					}
				}
				for(var sec in page){
					if(page[sec] && (page[sec].topicId == item.topicId)){
						section = page[sec];
						if(section){
							added = true;
							var replyItem;					
							if(section.posts.length > 0 && item.replies && (replyItem = replyRetriever(section.posts[0], item.replies))) {
								//alert("yes")
								replyItem.replies = storage.items.get({where: {parentId: replyItem.id }});
								section.posts.unshift(replyItem);
								section.posts.unshift(item);
								section.onlyPost = null;
								page.forEach(function(sec){
									if(sec.onlyPost == replyItem.id)
										sec.skip = true;
								});
								processedItems.push(item.id);
								processedItems.push(replyItem.id);
								if(item.isUserReply){
									section.replyToComment = item.toUserId;
									section.replyToId = item.parentId;
								} else {
									section.replyToComment = null;
								}
								(section.conversationWith) 
									? (section.conversationWith.indexOf(replyItem.userId) < 0) 
										? section.conversationWith.push(replyItem.userId)
										: null 
									: section.conversationWith = [replyItem.userId];
								
								if(section.replyToComment == section.conversationWith){
									section.replyToComment = null;
									
									starterFinder(item);
								}
								if(section.conversationWith && section.posts[section.posts.length - 1].replies && (section.posts[section.posts.length - 1].userId == section.user)){
									section.posts[section.posts.length - 1].replies.forEach(function(reply){
										var replyItem = reply.value;
										if(section.conversationWith.indexOf(replyItem.userId) > -1 || (request.params.user && typeof(request.params.user) == "object" && request.params.user.indexOf(replyItem.userId) > -1)){
											if(section.conversationWith.indexOf(replyItem.userId) < 0){
												section.conversationWith.push(replyItem.userId);
											}
											replyItem.replies = storage.items.get({where: {parentId: replyItem.id }});
											section.posts.push(replyItem);
											processedItems.push(replyItem.id);
										}
									});
								}
								break;
							
							} else {
								added = false;
							}
						}
					}
				}
								
				
				if(!added){
					section = {topicId: item.topicId, posts: [item], onlyPost: item.id, user: item.userId, replyToComment: (item.isUserReply) ? item.toUserId : null, replyToId: (item.isUserReply) ? item.parentId : null}
					var moveUp;
					processedItems.push(item.id);
					if(section.posts[section.posts.length - 1].replies ){
						section.posts[section.posts.length - 1].replies.forEach(function(reply){
							var replyItem = reply.value;
							if(request.params.user && (request.params.user == replyItem.userId || (typeof(request.params.user) == "object" && request.params.user.indexOf(replyItem.userId) > -1))){
									(section.conversationWith)
										? section.conversationWith.push(replyItem.userId)
										: section.conversationWith = [replyItem.userId];
								
								
								
								
								replyItem.replies = storage.items.get({where: {parentId: replyItem.id }});
								section.posts.push(replyItem);
								processedItems.push(replyItem.id);
								section.onlyPost = null;
								page.forEach(function(sec){
									if(sec.onlyPost == replyItem.id)
										sec.skip = true;
								});
								starterFinder(item)
								moveUp = true;
								
							}
						});
						
					}
					 page.unshift(section);
					
				}
			}
		});
		
		
		page.forEach(function(section){
			if(!section.skip){
				var container = [];
				container.push("<div class='hf-sec'><p>");
				(section.conversationWith)
					? container.push("<a href='http://news.ycombinator.com/user?id=" + section.user + "' class='user'>" + section.user + "</a>" + conversationUsersString(section.conversationWith) + "engaged in a conversation")
					: container.push("<a href='http://news.ycombinator.com/user?id=" + section.user + "' class='user'>" + section.user + "</a>");
				(!section.conversationWith)
					? (section.replyToComment)
						?  container.push(" replied to a <a href='http://news.ycombinator.com/item?id=" + section.replyToId + "'>comment</a> by <a href='/hackerfeed/"+section.replyToComment+"?" + request.queryString + "' class='insite'>" +section.replyToComment+ "</a>")
						: container.push(" commented")
					: (section.replyToComment && section.replyToId)
						? container.push(" about a <a href='http://news.ycombinator.com/item?id=" + section.replyToId + "'>comment</a> by <a href='/hackerfeed/"+section.replyToComment+"?" + request.queryString + "' class='insite'>" +section.replyToComment+ "</a>")
						: "";
				
				container.push(" on the post: <a href='http://news.ycombinator.com/item?id=" + section.posts[0].topicId + "'>"  + section.posts[0].topicText + "</a></p><ul>");
				var convoHappened = "";
				section.posts.forEach(function(post, i){
					container.push("<li class='" + ((section.conversationWith && (post.userId != section.user)) ? "convo" : "comment") + "'><div id='c-"+post.id+"'>");
					//container.push("<li>" + ((post.isUserReply) ? "<p><a href='#'>@"+ post.toUserId +"</a>: " : ""));
					var postHTML = post.commentHTML.replace(/<a.+?>(.*?)<\/a>/g,"$1");
					postHTML = ((postHTML.length > 500) ? $("<wrap />").append(postHTML.replace(/<a.+?>(.*?)<\/a>/g,"$1").substr(0, 500).replace(/\/pre>/g,"/pre><p>")).html().replace(/<\/i><\/p>$/,"... <a href='http://news.ycombinator.com/item?id=" + post.id + "' onclick='this.blur();$(this).addClass(\"loading\");$(\"#c-"+post.id+"\").load(\"/ajax/comment/"+post.id+((post.userId != section.user)? "?showuser=1":"")+"\");return false;' class='insite more'>more</a></i></p>").replace(/([^>])<\/p>$/,"$1... <a href='http://news.ycombinator.com/item?id=" + post.id + "' onclick='this.blur();$(this).addClass(\"loading\");$(\"#c-"+post.id+"\").load(\"/ajax/comment/"+post.id+((post.userId != section.user)? "?showuser=1":"")+"\");return false;' class='insite more'>more</a></p>").replace(/<\/pre>$/,"<p>... <a href='http://news.ycombinator.com/item?id=" + post.id + "' onclick='this.blur();$(this).addClass(\"loading\");$(\"#c-"+post.id+"\").load(\"/ajax/comment/"+post.id+((post.userId != section.user)? "?showuser=1":"")+"\");return false;' class='insite more'>more</a></p>").replace(/<p\/>/g,"") : post.commentHTML.replace(/\/pre>(.*[^<])$/g,"/pre><p>$1</p>")).replace(/<p\/>/g,"").replace(/<p><i>/g,"<p class='quote'><i class='equote'>");
					if(post.userId != section.user)
						postHTML = postHTML.replace(/^<p( cl|><)/, "<p><a href='/hackerfeed/"+ post.userId +"?" + request.queryString + "' class='insite'>" + post.userId + "</a>:</p><p$1").replace(/^<p>([^<])/, "<p><a href='/hackerfeed/" + post.userId+"?" + request.queryString + "' class='insite'>" + post.userId + "</a>: $1"); 
					container.push(postHTML);
					container.push("</div><span class='sub'>" + post.points);
					container.push(" - " + prettyDate.convert(post.pubDate.toString("yyyy-MM-ddTHH:mm:ssZ")));
					var removeOne = (section.conversationWith && i != section.posts.length - 1) ? 1 : 0;
					var replies = post.replies.length - removeOne;
					container.push((replies > 0) 
						? " - <a href='http://news.ycombinator.com/item?id=" + post.id + "' onclick='if($(\"#r-"+post.id+"\").text() == \"\"){var that = this;this.blur();$(this).addClass(\"loading\");$(\"#r-"+post.id+"\").load(\"/ajax/replies/"+post.id+((post.userId != section.user)? "?showuser=1":"")+"\",null, function(){$(that).removeClass(\"loading\")})}else{$(\"#r-"+post.id+"\").text(\"\")};return false;' class='insite show'>" + ((replies > 1) ? replies + " replies" : "1 reply").replace(/r/,(removeOne == 1) ? "other r" : "r") + "</a>"
						: "");
					container.push(" - <a href='http://news.ycombinator.com/item?id=" + post.id + "'>link</a></span><div id='r-" + post.id + "'></div></li>");
				});
				container.push("</ul></div>");
				output.unshift(container.join(""));
			}
		});
		
	
			
		if(!request.uri.tokens.user){
			if(output.length > 1){
				$("#content").html(output.join(""));
				$("#content").prepend("<h2>viewing feeds for hackers you are following:</h2>");
				$("#sidenav").prepend("<h3>following:</h3>");
			}
		} else {
			$("#content").html(output.join(""));
			if(request.queryString != "null")
				$("#sidenav").prepend("<h3><a class='insite' href='/hackerfeed?"+request.queryString+"'>view all following</a></h3>");
			$("#content").prepend("<h2>viewing " + request.uri.tokens.user+ "'" + (/s$/.test(request.uri.tokens.user) ? "" : "s") + " hacker feed:</h2>");
		}
		
		
		if(typeof(request.params.user) == "string" ||(typeof(request.params.user) == "object" && request.params.user.length == 2 && request.params.user.indexOf("") > -1)){
			var user;
			if(typeof(request.params.user) == "object"){
				request.params.user.forEach(function(_user){
					if(_user!="") 
						user = _user;
				})
			}  else {
				user = request.params.user;
			}
			
			$("#hackerlist").prepend((user) ? "<a class='info' href='/hackerfeed'>remove</a> <span class='info'> - </span><a href='/hackerfeed/"+ user+"?" + request.queryString + "' class='insite' >"+ user+"</a><input type='hidden' name='user' value='"+ user+"' /><br />" : "");
			
			
		} else if(typeof(request.params.user) == "object"){
			var userInputs = [], done =[];
			request.params.user.forEach(function(user){
				if((user != "") && (done.indexOf(user)< 0 )){
					done.push(user);
									
					userInputs.push("<a class='info' href='"+request.uri.toString()+"?" + request.queryString.replace(new RegExp("user=" + user + "&?", "g"), "").replace(/user=$/, "").replace(/&$/, "") + "'>remove</a> <span class='info'> - </span>")
					userInputs.push("<a href='/hackerfeed/"+user+"?" + request.queryString + "' class='insite' >"+ user+"</a><input type='hidden' name='user' value='"+ user+"' /><br/>");
				}
			});
			$("#hackerlist").prepend(userInputs.join(""));
			
		}
		
		if(request.uri.tokens.user && !((request.params.user == request.uri.tokens.user) || (request.params.user && typeof(request.params.user) == "object" && request.params.user.indexOf(request.uri.tokens.user) > -1))){
				$("#hackerfeed-user").val(request.uri.tokens.user);
		}
	}
	
	this.post = function(){
		this.get();
	}
}

